package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.minio.MinIOService;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.WmMaterialDto;
import com.heima.media.entity.WmMaterial;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.mapper.WmMaterialMapper;
import com.heima.media.service.IWmMaterialService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.media.service.IWmNewsMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 自媒体图文素材信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-12
 */
@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements IWmMaterialService {


    @Autowired
    private MinIOService minIOService;
    @Autowired
    private IWmNewsMaterialService newsMaterialService;

    @Override
    public ResponseResult<WmMaterial> upload(MultipartFile file) {

        // 用户id从本地线程中获取
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 调用minio上传图片,获取url地址
        String url = minIOService.upload(file);
        // 构建素材对象,存入到数据库中
        WmMaterial material = new WmMaterial();
        material.setUserId(user.getUserId());
        material.setUrl(url);
        material.setType(0);
        material.setIsCollection(false);
        material.setCreatedTime(new Date());
        this.save(material);
        return ResponseResult.okResult(material);
    }

    @Override
    public ResponseResult listByCollection(WmMaterialDto dto) {
        // 用户id从本地线程中获取
        User user = MediaThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 查询条件
        LambdaQueryWrapper<WmMaterial> query = new LambdaQueryWrapper<>();
        // 只能查询用户自己上传的图片
        query.eq(WmMaterial::getUserId, user.getUserId());
        if (dto.getIsCollection() != null) {
            query.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        // 按照创建时间倒序排列
        query.orderByDesc(WmMaterial::getCreatedTime);
        // 分页查询
        IPage<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> iPage = this.page(page, query);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(),
                iPage.getTotal(), iPage.getRecords());
        return result;
    }

    @Override
    public ResponseResult collect0(Integer materialId) {

        WmMaterial wmMaterial = getById(materialId);
        //如果没有返回不存在
        if(wmMaterial==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //判断幂等性
        if(wmMaterial.getIsCollection())
            return ResponseResult.okResult();
        wmMaterial.setIsCollection(true);
        //操作数据库更新，这个流程短不用异步
        updateById(wmMaterial);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult cancelCollect0(Integer materialId) {
        WmMaterial wmMaterial = getById(materialId);
        //判断是否合法参数
        if(wmMaterial==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        //判断幂等性
        if(!wmMaterial.getIsCollection())
            return ResponseResult.okResult();
        wmMaterial.setIsCollection(false);
        updateById(wmMaterial);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult doDelete(Integer materialId) {
        //首先去中间表查看有无对应的素材id
        LambdaQueryWrapper<WmNewsMaterial> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmNewsMaterial::getMaterialId,materialId);
        int count = newsMaterialService.count(queryWrapper);
        //如果存在关联，不允许删除
        if(count!=0)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        LambdaUpdateWrapper<WmNewsMaterial> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(WmNewsMaterial::getMaterialId,materialId);
        removeById(materialId);
        return ResponseResult.okResult();
    }


}
